{% extends "base_generic.html" %}
{% load static %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
  .star-rating {
    color: #ffd700;
    cursor: pointer;
  }
  .star-rating.disabled {
    cursor: default;
  }
  .like-btn, .favorite-btn {
    cursor: pointer;
    transition: color 0.3s;
  }
  .like-btn.active {
    color: #e74c3c;
  }
  .favorite-btn.active {
    color: #f1c40f;
  }
  .review-card {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
  }
  .review-meta {
    color: #666;
    font-size: 0.9em;
  }
  .book-cover {
    max-width: 300px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
  }
  .book-price {
    font-size: 1.5em;
    color: #27ae60;
    margin: 15px 0;
  }
  .book-actions {
    margin: 20px 0;
  }
  .book-stats {
    display: flex;
    gap: 20px;
    margin: 15px 0;
  }
  .stat-item {
    display: flex;
    align-items: center;
    gap: 5px;
  }
</style>
{% endblock %}

{% block content %}
<div class="container py-4">
  <div class="row">
    <!-- 左侧图书信息 -->
    <div class="col-md-4 mb-4">
      <div class="card">
        {% if book.cover_image %}
        <img src="{{ book.cover_image.url }}" class="card-img-top book-cover" alt="{{ book.title }}">
        {% else %}
        <div class="card-img-top book-cover d-flex align-items-center justify-content-center bg-light">
          <i class="fas fa-book fa-5x text-muted"></i>
        </div>
        {% endif %}
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-center mb-3">
            {% if book.price %}
            <h5 class="mb-0">¥{{ book.price }}</h5>
            {% endif %}
            <div class="btn-group">
              {% if user.is_authenticated %}
              <button class="btn btn-outline-danger favorite-btn" data-book-id="{{ book.id }}">
                <i class="{% if user in book.favorites.all %}fas{% else %}far{% endif %} fa-heart"></i>
                <span class="favorite-count">{{ book.favorites.count }}</span>
              </button>
              <button class="btn btn-outline-primary like-btn" data-book-id="{{ book.id }}">
                <i class="{% if user in book.likes.all %}fas{% else %}far{% endif %} fa-thumbs-up"></i>
                <span class="like-count">{{ book.likes.count }}</span>
              </button>
              {% endif %}
            </div>
          </div>
          
          <div class="book-meta">
            <p class="mb-2">
              <i class="fas fa-language"></i> 语言：
              <a href="{{ book.language.get_absolute_url }}" class="text-decoration-none">
                {{ book.language }}
              </a>
            </p>
            <p class="mb-2">
              <i class="fas fa-barcode"></i> ISBN：{{ book.isbn }}
            </p>
            {% if book.publication_date %}
            <p class="mb-2">
              <i class="fas fa-calendar-alt"></i> 出版日期：{{ book.publication_date }}
            </p>
            {% endif %}
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧内容 -->
    <div class="col-md-8">
      <div class="card mb-4">
        <div class="card-body">
          <h1 class="card-title display-5 mb-3">{{ book.title }}</h1>
          <h6 class="card-subtitle mb-3">
            {% if book.author %}
            <a href="{{ book.author.get_absolute_url }}" class="text-decoration-none">
              <i class="fas fa-user-edit"></i> {{ book.author }}
            </a>
            {% endif %}
          </h6>

          <div class="genres mb-3">
            {% for genre in book.genre.all %}
            <a href="{% url 'books' %}?genre={{ genre.id }}" class="text-decoration-none">
              <span class="badge bg-secondary">{{ genre.name }}</span>
            </a>
            {% endfor %}
          </div>

          <div class="rating-section mb-4">
            <h5>评分</h5>
            {% if book.average_rating %}
            <div class="rating">
              {% for i in "12345"|make_list %}
              {% if forloop.counter <= book.average_rating|floatformat:"0" %}
              <i class="fas fa-star"></i>
              {% else %}
              <i class="far fa-star"></i>
              {% endif %}
              {% endfor %}
              <span class="ms-2">{{ book.average_rating|floatformat:1 }}</span>
              <small class="text-muted">({{ book.bookrating_set.count }}评分)</small>
            </div>
            {% else %}
            <p class="text-muted">暂无评分</p>
            {% endif %}

            {% if user.is_authenticated %}
            <form class="rating-form mt-2" method="post" action="{% url 'book-rate' book.id %}">
              {% csrf_token %}
              <div class="btn-group" role="group">
                {% for i in "12345"|make_list %}
                <input type="radio" class="btn-check" name="rating" id="rating{{ i }}" value="{{ i }}"
                  {% if user_rating == i|add:"0" %}checked{% endif %}>
                <label class="btn btn-outline-warning" for="rating{{ i }}">{{ i }}</label>
                {% endfor %}
              </div>
              <button type="submit" class="btn btn-primary ms-2">提交评分</button>
            </form>
            {% endif %}
          </div>

          <div class="summary-section mb-4">
            <h5>简介</h5>
            <p class="card-text">{{ book.summary }}</p>
          </div>

          <div class="copies-section mb-4">
            <h5>馆藏信息</h5>
            <div class="table-responsive">
              <table class="table">
                <thead>
                  <tr>
                    <th>副本ID</th>
                    <th>状态</th>
                    <th>借阅者</th>
                    <th>归还日期</th>
                  </tr>
                </thead>
                <tbody>
                  {% for copy in book.bookinstance_set.all %}
                  <tr>
                    <td>{{ copy.id }}</td>
                    <td>
                      <span class="badge {% if copy.status == 'a' %}bg-success{% elif copy.status == 'm' %}bg-warning{% elif copy.status == 'o' %}bg-danger{% else %}bg-secondary{% endif %}">
                        {{ copy.get_status_display }}
                      </span>
                    </td>
                    <td>{{ copy.borrower|default:"-" }}</td>
                    <td>{{ copy.due_back|default:"-" }}</td>
                  </tr>
                  {% endfor %}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="card">
        <div class="card-body">
          <h5 class="card-title mb-4">读者评论</h5>
          
          {% if user.is_authenticated %}
          <form method="post" action="{% url 'book-review' book.id %}" class="mb-4">
            {% csrf_token %}
            <div class="mb-3">
              <textarea class="form-control" name="review_text" rows="3" placeholder="写下你的评论..."></textarea>
            </div>
            <button type="submit" class="btn btn-primary">发表评论</button>
          </form>
          {% endif %}

          <div class="reviews">
            {% for review in book.bookreview_set.all %}
            <div class="review">
              <div class="d-flex justify-content-between align-items-start mb-2">
                <div>
                  <h6 class="mb-0">{{ review.user.username }}</h6>
                  <small class="text-muted">{{ review.created_at|date:"Y-m-d H:i" }}</small>
                </div>
                <div class="btn-group">
                  {% if user.is_authenticated %}
                  <button class="btn btn-sm btn-outline-primary review-like-btn" data-review-id="{{ review.id }}">
                    <i class="{% if user in review.likes.all %}fas{% else %}far{% endif %} fa-thumbs-up"></i>
                    <span class="review-like-count">{{ review.likes.count }}</span>
                  </button>
                  {% endif %}
                  {% if user == review.user %}
                  <form method="post" action="{% url 'review-delete' review.id %}" style="display: inline;">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-sm btn-outline-danger">
                      <i class="fas fa-trash"></i>
                    </button>
                  </form>
                  {% endif %}
                </div>
              </div>
              <p class="mb-0">{{ review.review_text }}</p>
            </div>
            {% empty %}
            <p class="text-muted">暂无评论</p>
            {% endfor %}
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
  // 收藏按钮
  const favoriteBtn = document.querySelector('.favorite-btn');
  if (favoriteBtn) {
    favoriteBtn.addEventListener('click', function() {
      const bookId = this.dataset.bookId;
      const icon = this.querySelector('i');
      const countSpan = this.querySelector('.favorite-count');
      
      fetch(`/catalog/book/${bookId}/favorite/`, {
        method: 'POST',
        headers: {
          'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
        },
      })
      .then(response => response.json())
      .then(data => {
        if (data.is_favorite) {
          icon.classList.replace('far', 'fas');
        } else {
          icon.classList.replace('fas', 'far');
        }
        countSpan.textContent = data.favorite_count;
      });
    });
  }

  // 点赞按钮
  const likeBtn = document.querySelector('.like-btn');
  if (likeBtn) {
    likeBtn.addEventListener('click', function() {
      const bookId = this.dataset.bookId;
      const icon = this.querySelector('i');
      const countSpan = this.querySelector('.like-count');
      
      fetch(`/catalog/book/${bookId}/like/`, {
        method: 'POST',
        headers: {
          'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
        },
      })
      .then(response => response.json())
      .then(data => {
        if (data.is_liked) {
          icon.classList.replace('far', 'fas');
        } else {
          icon.classList.replace('fas', 'far');
        }
        countSpan.textContent = data.like_count;
      });
    });
  }

  // 评论点赞按钮
  const reviewLikeBtns = document.querySelectorAll('.review-like-btn');
  reviewLikeBtns.forEach(button => {
    button.addEventListener('click', function() {
      const reviewId = this.dataset.reviewId;
      const icon = this.querySelector('i');
      const countSpan = this.querySelector('.review-like-count');
      
      fetch(`/catalog/review/${reviewId}/like/`, {
        method: 'POST',
        headers: {
          'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
        },
      })
      .then(response => response.json())
      .then(data => {
        if (data.is_liked) {
          icon.classList.replace('far', 'fas');
        } else {
          icon.classList.replace('fas', 'far');
        }
        countSpan.textContent = data.like_count;
      });
    });
  });
});
</script>
{% endblock %}


{% block sidebar %}
  {{ block.super }}

  {% if perms.catalog.change_book or perms.catalog.delete_book %}
  <hr>
  <ul class="sidebar-nav">
    {% if perms.catalog.change_book %}
      <li><a href="{% url 'book-update' book.id %}">Update Book</a></li>
    {% endif %}
    {% if not book.bookinstance_set.all and perms.catalog.delete_book %}
      <li><a href="{% url 'book-delete' book.id %}">Delete Book</a></li>
    {% endif %}
    </ul>
  {% endif %}

{% endblock %}
